// pages/report-query/report-query.js
Page({
  data: {
    patientInfo: {
      name: '',
      relation: '本人',
      idNumber: ''
    },
    showPatientModal: false,
    showTimePicker: false,
    patientList: [],
    reportList: [
      // 2025年数据
      { id: 1, title: '肝功能常规检查报告', department: '内科', doctor: '刘美', dateTime: '2025-01-15 11:05', type: 'laboratory' },
      { id: 2, title: '血常规检查报告', department: '内科', doctor: '张医生', dateTime: '2025-02-20 14:30', type: 'laboratory' },
      { id: 3, title: '心电图检查报告', department: '心内科', doctor: '李医生', dateTime: '2025-03-10 09:15', type: 'examination' },
      { id: 4, title: '胸部X光检查报告', department: '放射科', doctor: '王医生', dateTime: '2025-04-05 16:45', type: 'examination' },
      { id: 5, title: '病理检查报告', department: '病理科', doctor: '陈医生', dateTime: '2025-05-12 10:20', type: 'pathology' },
      { id: 6, title: '体检报告', department: '体检科', doctor: '赵医生', dateTime: '2025-06-08 09:30', type: 'physical' },
      // 2024年数据
      { id: 7, title: '肾功能检查报告', department: '内科', doctor: '孙医生', dateTime: '2024-07-15 14:20', type: 'laboratory' },
      { id: 8, title: 'B超检查报告', department: '超声科', doctor: '周医生', dateTime: '2024-08-22 10:45', type: 'examination' },
      { id: 9, title: '胃镜检查报告', department: '消化内科', doctor: '吴医生', dateTime: '2024-09-25 08:45', type: 'examination' },
      // 2023年数据
      { id: 10, title: '病理切片检查报告', department: '病理科', doctor: '郑医生', dateTime: '2023-03-12 16:15', type: 'pathology' },
      { id: 11, title: '核磁共振检查报告', department: '放射科', doctor: '林医生', dateTime: '2023-05-18 11:30', type: 'examination' },
      // 2022年数据
      { id: 12, title: 'CT检查报告', department: '放射科', doctor: '黄医生', dateTime: '2022-02-14 13:20', type: 'examination' },
      { id: 13, title: '血液病理检查报告', department: '病理科', doctor: '马医生', dateTime: '2022-04-30 15:10', type: 'pathology' },
      // 2021年数据
      { id: 14, title: '肿瘤标志物检查报告', department: '肿瘤科', doctor: '朱医生', dateTime: '2021-07-03 09:00', type: 'laboratory' },
      { id: 15, title: '骨髓检查报告', department: '血液科', doctor: '胡医生', dateTime: '2021-11-28 14:50', type: 'pathology' },
      // 2020年数据
      { id: 16, title: '急诊检查报告', department: '急诊科', doctor: '郭医生', dateTime: '2020-01-10 20:30', type: 'examination' },
      { id: 17, title: '康复评估报告', department: '康复科', doctor: '何医生', dateTime: '2020-12-05 10:15', type: 'examination' }
    ],
    filteredReportList: [],
    activeFilter: 'year',
    // 时间选择器数据
    years: [2020, 2021, 2022, 2023, 2024, 2025],
    months: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
    days: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
    startPickerValue: [5, 0, 0], // 默认选择2025年01月01日
    endPickerValue: [5, 11, 30], // 默认选择2025年12月31日
    startDate: '2025年01月01日',
    endDate: '2025年12月31日',
    currentSelecting: 'start',
    pickerValue: [5, 0, 0]
  },

  onLoad(options) {
    console.log('报告查询页面加载');
    this.loadPatientInfo();
    // 初始化显示当前年份（2025年）的记录
    const currentYear = 2025;
    this.filterReportsByYear(currentYear);
  },

  // 加载就诊人信息
  loadPatientInfo() {
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let list = res.data
          if (typeof list === 'string') {
            try { list = JSON.parse(list) } catch (e) { return }
          }
          if (list.code !== undefined) list = list.data
          if (!Array.isArray(list)) return
          
          // 保存完整的就诊人列表
          const mapped = list.map(p => ({
            id: p.id,
            name: p.name,
            relation: p.relationTypeName || '本人',
            idNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
          }))
          
          this.setData({ patientList: mapped })
          
          // 找到默认就诊人
          const defaultPatient = list.find(p => p.isDefault === 1)
          if (defaultPatient) {
            this.setData({
              patientInfo: {
                name: defaultPatient.name,
                relation: defaultPatient.relationTypeName || '本人',
                idNumber: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
              }
            })
          } else {
            // 如果没有默认就诊人，使用第一个就诊人
            const firstPatient = list[0]
            if (firstPatient) {
              this.setData({
                patientInfo: {
                  name: firstPatient.name,
                  relation: firstPatient.relationTypeName || '本人',
                  idNumber: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2')
                }
              })
            }
          }
        }
      }
    })
  },

  // 切换就诊人
  switchPatient() {
    this.setData({
      showPatientModal: true
    });
  },

  // 关闭就诊人模态框
  closePatientModal() {
    this.setData({
      showPatientModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 选择就诊人
  selectPatient(e) {
    const patient = e.currentTarget.dataset.patient;
    console.log('选择了就诊人:', patient);
    
    this.setData({
      patientInfo: patient,
      showPatientModal: false
    });

    // 保存到本地存储
    const cacheUser = wx.getStorageSync('userInfo') || {}
    wx.setStorageSync('userInfo', { ...cacheUser, patientId: patient.id })
  },

  // 选择时间范围
  selectTimeRange(e) {
    const range = e.currentTarget.dataset.range;
    console.log('选择时间范围:', range);
    
    this.setData({
      activeFilter: range
    });
    
    if (range === 'year') {
      // 显示当前年份（2025年）的记录
      const currentYear = 2025;
      this.filterReportsByYear(currentYear);
    }
  },

  // 显示时间选择器
  showTimePicker() {
    this.setData({
      showTimePicker: true,
      currentSelecting: 'start',
      pickerValue: this.data.startPickerValue
    });
  },

  // 关闭时间选择器
  closeTimePicker() {
    this.setData({
      showTimePicker: false
    });
  },

  // 选择开始日期
  selectStartDate() {
    this.setData({
      currentSelecting: 'start',
      pickerValue: this.data.startPickerValue
    });
  },

  // 选择结束日期
  selectEndDate() {
    this.setData({
      currentSelecting: 'end',
      pickerValue: this.data.endPickerValue
    });
  },

  // 时间选择器变化
  onPickerChange(e) {
    const value = e.detail.value;
    const year = this.data.years[value[0]];
    const month = this.data.months[value[1]];
    const day = this.data.days[value[2]];
    const dateString = `${year}年${month}月${day}日`;
    
    if (this.data.currentSelecting === 'start') {
      this.setData({
        startPickerValue: value,
        startDate: dateString,
        pickerValue: value
      });
    } else {
      this.setData({
        endPickerValue: value,
        endDate: dateString,
        pickerValue: value
      });
    }
  },

  // 确认时间范围
  confirmTimeRange() {
    console.log('确认时间范围:', this.data.startDate, '至', this.data.endDate);
    
    // 根据选择的日期范围筛选报告
    this.filterReportsByDateRange(this.data.startDate, this.data.endDate);
    
    this.setData({
      showTimePicker: false,
      activeFilter: 'custom'
    });
  },

  // 查看报告详情
  viewReportDetail(e) {
    const report = e.currentTarget.dataset.report;
    console.log('查看报告详情:', report);
    
    // 根据报告类型跳转到不同页面
    switch (report.type) {
      case 'physical':
        // 体检报告跳转到体检报告页面
        wx.navigateTo({
          url: `/pages/health-report/health-report?report=${JSON.stringify(report)}`
        });
        break;
      default:
        // 其他报告跳转到报告详情页面
        wx.navigateTo({
          url: `/pages/report-detail/report-detail?report=${JSON.stringify(report)}`
        });
        break;
    }
  },

  // 根据年份筛选报告
  filterReportsByYear(year) {
    const filteredList = this.data.reportList.filter(item => {
      const itemYear = parseInt(item.dateTime.split('-')[0]);
      return itemYear === year;
    });
    
    this.setData({
      filteredReportList: filteredList
    });
  },

  // 根据日期范围筛选报告
  filterReportsByDateRange(startDate, endDate) {
    // 解析日期字符串
    const startYear = parseInt(startDate.match(/(\d{4})年/)[1]);
    const startMonth = parseInt(startDate.match(/(\d{1,2})月/)[1]);
    const startDay = parseInt(startDate.match(/(\d{1,2})日/)[1]);
    
    const endYear = parseInt(endDate.match(/(\d{4})年/)[1]);
    const endMonth = parseInt(endDate.match(/(\d{1,2})月/)[1]);
    const endDay = parseInt(endDate.match(/(\d{1,2})日/)[1]);
    
    const startDateObj = new Date(startYear, startMonth - 1, startDay);
    const endDateObj = new Date(endYear, endMonth - 1, endDay);
    
    const filteredList = this.data.reportList.filter(item => {
      const itemDate = new Date(item.dateTime.split(' ')[0]);
      return itemDate >= startDateObj && itemDate <= endDateObj;
    });
    
    this.setData({
      filteredReportList: filteredList
    });
  }
});
